<template>
  <div>
    <!-- 三级全局分类组件 -->
    <Category :scene="scene" />
    <el-card class="mt-5">
      <div v-show="scene == 0">
        <el-button
          type="primary"
          icon="Plus"
          :disabled="categoryStore.c3Id ? false : true"
          @click="addAttr"
          >添加品牌</el-button
        >
        <el-table :data="attrArr" class="mt-3" border>
          <el-table-column
            label="序号"
            property="id"
            type="index"
            align="center"
            width="150px"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            property="attrName"
            width="150px"
          ></el-table-column>
          <el-table-column
            label="属性值名称"
            property="attrValueList.valueName"
          >
            <template #="{ row }">
              <el-tag
                v-for="item in row.attrValueList"
                :key="item.id"
                type="success"
                class="ml-2"
                >{{ item.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150px">
            <!-- row:已有属性 -->
            <template #="{ row }">
              <el-button
                size="small"
                type="warning"
                icon="Edit"
                @click="updateAttr(row)"
              ></el-button>
              <!-- 删除 -->
              <el-popconfirm
                width="220"
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon="Delete"
                icon-color="#626AEF"
                title="是否删除数据"
                @confirm="removeAttr(row.id)"
              >
                <template #reference>
                  <el-button
                    size="small"
                    type="danger"
                    icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-show="scene == 1">
        <!-- 展示添加属性与修改数据的结构 -->
        <el-form :inline="true">
          <el-form-item label="属性的名称">
            <el-input
              placeholder="请输入属性名称"
              v-model="attrParams.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          size="default"
          :disabled="attrParams.attrName ? false : true"
          @click="addAttrValue"
          icon="Plus"
          >添加属性值</el-button
        >
        <el-button type="primary" size="default" @click="cancel"
          >取消</el-button
        >
        <el-table :data="attrParams.attrValueList" class="mt-3" border>
          <el-table-column
            label="序号"
            property="id"
            type="index"
            align="center"
            width="150px"
          ></el-table-column>
          <el-table-column label="属性名称">
            <!-- row:即为当前属性值的对象 -->
            <template #="{ row, $index }">
              <el-input
                :ref="(vc: any) => (inputArr[$index] = vc)"
                v-if="row.flag"
                placeholder="请输入属性值的名称"
                v-model="row.valueName"
                @blur="toLook(row, $index)"
              ></el-input>
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="属性值操作" align="center">
            <template #="{ $index }">
              <el-button
                type="danger"
                icon="Delete"
                size="small"
                @click="attrParams.attrValueList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          size="default"
          @click="save"
          :disabled="attrParams.attrValueList.length > 0 ? false : true"
          >保存</el-button
        >
        <el-button type="primary" @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage } from "element-plus";
//组合式API函数watch
import { ref, watch, reactive, nextTick, onBeforeUnmount } from "vue";
// 引入获取已有属性与属性值接口
import {
  reqAttr,
  reqAddOrUpdateAttr,
  reqRemoveAttr,
} from "@/api/product/attr/index";
import type {
  AttrResponseData,
  Attr,
  AttrValue,
} from "@/api/product/attr/type";
import useCategoryStore from "@/store/modules/category";
let categoryStore = useCategoryStore();
//定义card组件内容切换变量
const scene = ref<number>(0); //scene=0,显示table,scene=1,展示添加与修改的属性结构
//收集新增的属性的数据
let attrParams = reactive<Attr>({
  id: 0,
  attrName: "", //新增属性的名字
  attrValueList: [
    //新增的属性值的数组
  ],
  categoryId: "", //三级标题的id
  categoryLevel: 3, //代表的是三级分类
});
//准备一个数组:将来存储对应的组件实例el-input
let inputArr = ref<any>([]);
//声明
const attrArr = ref<Attr[]>([]);
//监听仓库中的c3Id是否出现变化
watch(
  () => categoryStore.c3Id,
  () => {
    //清空上一次查询的属性与属性值
    attrArr.value = [];
    //保证三级分类得有才能发请求
    if (!categoryStore.c3Id) return;
    getAttr();
  }
);
//获取已有的属性与属性值方法
const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore;
  // 获取分类下的已有的属性与属性值
  const result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id);
  if (result.code == 200) {
    attrArr.value = result.data;
  }
};
//添加属性按钮的回调
const addAttr = () => {
  //清空数据在收集数据
  Object.assign(attrParams, {
    attrName: "", //新增属性的名字
    attrValueList: [
      //新增的属性值的数组
    ],
    //点击按钮的时候收集新增属性的三级分类的id
    categoryId: categoryStore.c3Id, //三级标题的id
    categoryLevel: 3, //代表的是三级分类
  });
  //切换添加属性
  scene.value = 1;
};
//table表格修改已有属性按钮的回调
const updateAttr = (row: any) => {
  //切换为添加与修改属性的结构
  scene.value = 1;
  //将已有的属性对象赋值给attrParams对象即为
  //ES6=>Object.assign进行对象的合并   知识点:浅拷贝与深拷贝的应用概念
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)));
  // attrParams.attrName = row.attrName
  // attrParams.attrValueList = row.attrValueList
  // attrParams.categoryId = row.categoryId
};
//取消按钮的回调
const cancel = () => {
  scene.value = 0;
};
//添加属性值按钮的回调
const addAttrValue = () => {
  //点击添加属性值按钮的时候,向数组添加一个属性值对象
  attrParams.attrValueList.push({
    attrId: "",
    valueName: "",
    flag: true, //控制每一个属性值的编辑模式与切换模式的切换
  });
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  });
};
//点击保存按钮的回调
const save = async () => {
  //收集参数
  //发送请求
  let result: any = await reqAddOrUpdateAttr(attrParams);
  console.log(result);
  if (result.code == 200) {
    // 切换场景
    scene.value = 0;
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改成功" : "添加成功 ",
    });
    //获取全部的已有的属性与属性值
    getAttr();
  } else {
    ElMessage({
      type: "error",
      message: attrParams.id ? "修改失败" : "添加失败 ",
    });
  }
};
//属性值表单元素失去焦点事件回调
const toLook = (row: AttrValue, $index: number) => {
  if (row.valueName.trim() == "") {
    attrParams.attrValueList.splice($index, 1);
    ElMessage({
      type: "error",
      message: "属性值不能为空",
    });
    return;
  }
  row.flag = false;
  let repeat = attrParams.attrValueList.find((item) => {
    //切记把当前失去焦点的属性值对象从前当前
    if (item != row) {
      // attrParams.attrValueList.splice($index,1)
      return item.valueName === row.valueName;
    }
  });
  if (repeat) {
    //将重复的属性值从数组中删除
    attrParams.attrValueList.splice($index, 1);
    ElMessage({
      type: "error",
      message: "属性值不能重复",
    });
  }
};
const toEdit = (row: AttrValue, $index: number) => {
  row.flag = true;
  // nextTick:是响应式数据发生变化.获取更新的Dom(组件实例)
  nextTick(() => {
    inputArr.value[$index].focus();
  });
};
//删除
const removeAttr = async (attrId: number) => {
  const result: any = await reqRemoveAttr(attrId);
  getAttr();
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "删除成功!",
    });
  } else {
    ElMessage({
      type: "error",
      message: "删除失败!",
    });
  }
};
//路由组件销毁的时候,把仓库分类相关的数据清空
onBeforeUnmount(() => {
  categoryStore.$reset();
});
</script>

<style lang="scss" scoped></style>
